import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { ModalController, NavParams } from '@ionic/angular';
import { pb } from 'src/pb';
import { formSetValues } from '../components/formSetValues';
import { HttpService } from '../http.service';

@Component({
  selector: 'app-config',
  templateUrl: './config.page.html',
  styleUrls: ['./config.page.scss'],
})
export class ConfigPage implements OnInit {
  form = this.fb.group({
    port: [
      3306,
      [Validators.required, Validators.min(80), Validators.max(100000)],
    ],
    webPort: [
      8080,
      [Validators.required, Validators.min(80), Validators.max(100000)],
    ],
    defaultLimit: [
      1000,
      [Validators.required, Validators.min(10), Validators.max(10000)],
    ],
  });
  private config: pb.IConfig = {};
  constructor(
    params: NavParams,
    private fb: FormBuilder,
    private http: HttpService,
    private modalCtrl: ModalController
  ) {
    this.config = params.data.config;
    formSetValues(this.form, this.config);
  }

  ngOnInit() {}
  close() {
    return this.modalCtrl.dismiss();
  }

  async onSubmit() {
    Object.assign(this.config, this.form.value);
    await this.modalCtrl.dismiss(
      await this.http.post('/api/config', this.config)
    );
  }
}
